package com.demo.kafka.consumer;



import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;
//自动提交 offset
public class AutoCommitConsumer {
    public static void main(String[] args) {

        //1、配置信息
        Properties properties = new Properties();
        //kafka集群
//        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:19092,localhost:19093,localhost:19094");
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:19092");
        //是否开启自动提交 offset 功能
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
        //自动提交 offset 的时间间隔
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
        //key值的反序列化
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //key值的反序列化
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
        //消费者组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "group_test");

        //2、创建消费者对象（Consumer）
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        //3、订阅主题，可订阅多个
        consumer.subscribe(Arrays.asList("fff", "zzz", "kkk", "first"));

        while (true){
            //4、拉取订阅的消息
            ConsumerRecords<String, String> consumerRecords = consumer.poll(100);
            //打印拉取到的消息
            for (ConsumerRecord<String, String> consumerRecord : consumerRecords) {
                System.out.println(consumerRecord.key() + " --- " + consumerRecord.value());
            }
        }
    }
}
